
/**
 * @version $Id$
 * @author xjiujiu <xjiujiu@foxmail.com>
 * @description HongJuZi Framework
 * @copyright Copyright (c) 2011-2012 http://www.xjiujiu.com.All right reserved
 */

HHJsLib.register({
    init: function() {
        $('div.goods-list-box').nestable({'maxDepth': 1});
        this.bindBtnGoodsAdd('a.btn-goods-add');
        this.bindBtnGoodsDel('a.btn-goods-del');
        this.bindBtnAddNewGoodsType();
        this.bindBtnGoodsItemDel('a.btn-goods-item-del');
        this.bindDrop();
        this.bindInfoFromSubmit();
        this.bindAddNewZenPing();
        this.bindAddNewYouHuiJuan();
        this.bindBtnInfoFormSubmit();
        this.bindBtnYouHuiJuanItemDel();
        this.bindBtnZenpingItemDel();
    },
    bindAddNewZenPing: function() {
        var self     = this;
        $('#btn-add-new-zenping').click(function() {
            var body= $('#search-zenping-body-template').html();
            $('#modal-body').html(body);
            $('#myModalLabel').html('添加赠品');
            $('#modal-footer').html($('#search-footer-template').html());
            $('#myModal').modal('show');
            self.bindBtnBatch();
            self.bindSearchZenPing();
        });
    },
    bindSearchZenPing: function() {
        var self    = this;
        $('#search-form').submit(function() {
            return self.doSearchZenPingList(1);
        });
    },
    doSearchZenPingList: function(page) {
        var self    = this;
        $.getJSON(
            queryUrl + 'admin/zenping/asearch',
            {keywords: $('#keywords').val(), page: page},
            function(response) {
                if(false === response.rs) {
                    return HHJsLib.warn(response.message);
                }
                self.initSearchTablePages(page, response);
                var tableTpl    = $('#search-zenping-result-template').html();
                var itemHtml    = self.getSearchZenPingListHtml(response.data);
                tableTpl        = tableTpl.replace(/{content}/g, itemHtml);
                $('#table-box').html(tableTpl);
                self.bindCheckAll();
                self.bindBtnAddZenPingToActivity();
                self.bindBtnPreNextSearchPages(function(page) {
                    self.doSearchZenPingList(page);
                });
            }
        );
        return false;
    },
    getSearchZenPingListHtml: function(list) {
        if(!list || 1 > list.length) {
            return '<tr><td colspan="9"><div  class="text-center">没有搜索到赠品哦～</div></td></tr>';
        }
        var itemTpl = $('#result-zenping-item-template').html();
        var tdHtml  = '';
        for(var ele in list) {
            var item    = list[ele];
            tdHtml      += itemTpl.replace(/{id}/g, item.id)
            .replace(/{name}/g, item.name)
            .replace(/{price}/g, item.price)
            .replace(/{src}/g, item.image_path)
            .replace(/{img}/g, item.image_path)
            .replace(/{number}/g, item.number)
            .replace(/{song}/g, item.song)
            .replace(/{last}/g, item.last_number);
        }

        return tdHtml;
    },
    bindBtnAddZenPingToActivity: function() {
        var self    = this;
        $('#table-box a.btn-add-search-goo').click(function() {
            var id  = $(this).attr('data-id');
            self.appendZenPingList(id);
            $('#search-item-' + id).fadeOut('fast', function() {
                $(this).remove();
            });
        });
    },
    appendZenPingList: function(id) {
        var tpl             = $('#sort-zenping-template').html();
        tpl                 = tpl.replace(/{number}/g, $('#number-' + id).text())
        .replace(/{name}/g, $('#name-' + id).text())
        .replace(/{id}/g, id)
        .replace(/{song}/g, $('#min-price-' + id).text())
        .replace(/{img}/g, $('#img-' + id).attr('data-small-src'))
        .replace(/{src}/g, $('#img-' + id).attr('data-src'))
        .replace(/{song}/g, $('#song-' + id).text())
        .replace(/{price}/g, $('#price-' + id).text())
        .replace(/{number}/g, $('#number-' + id).text())
        .replace(/{last_number}/g, $('#last-number-' + id).text());
        $('#zenping-list').append(tpl);
        this.bindBtnZenpingItemDel();
    },
    bindBtnZenpingItemDel: function() {
        $('#zenping-list a.btn-goods-item-del').unbind().click(function() {
            var id  = $(this).attr('data-id');
            if(!confirm('您真的要删除此项吗？')) {
                return;
            }
            $('#zenping-item-' + id).fadeOut(200, function() {
                $(this).remove();
            });
        });
    },
    bindAddNewYouHuiJuan: function() {
        var self     = this;
        $('#btn-add-new-youhuijuan').click(function() {
            var body= $('#search-youhuijuan-body-template').html();
            $('#modal-body').html(body);
            $('#myModalLabel').html('添加优惠券');
            $('#modal-footer').html($('#search-footer-template').html());
            $('#myModal').modal('show');
            self.bindBtnBatch();
            self.bindSearchYouHuiJuan();
        });
    },
    bindSearchYouHuiJuan: function() {
        var self    = this;
        $('#search-form').submit(function() {
            return self.doSearchYouHuiJuanList(1);
        });
    },
    doSearchYouHuiJuanList: function(page) {
        var self    = this;
        $.getJSON(
            queryUrl + 'admin/youhuijuan/asearch',
            {keywords: $('#keywords').val(), page: page},
            function(response) {
                if(false === response.rs) {
                    return HHJsLib.warn(response.message);
                }
                self.initSearchTablePages(page, response);
                var tableTpl    = $('#search-youhuijuan-result-template').html();
                var itemHtml    = self.getSearchYouHuiJuanListHtml(response.data);
                tableTpl        = tableTpl.replace(/{content}/g, itemHtml);
                $('#table-box').html(tableTpl);
                self.bindCheckAll();
                self.bindBtnAddYouHuiJuanToActivity();
                self.bindBtnPreNextSearchPages(function(page) {
                    self.doSearchYouHuiJuanList(page);
                });
            }
        );
        return false;
    },
    getSearchYouHuiJuanListHtml: function(list) {
        if(!list || 1 > list.length) {
            return '<tr><td colspan="9"><div  class="text-center">没有搜索到优惠券哦～</div></td></tr>';
        }
        var itemTpl = $('#result-youhuijuan-item-template').html();
        var tdHtml  = '';
        for(var ele in list) {
            var item    = list[ele];
            tdHtml      += itemTpl.replace(/{id}/g, item.id)
            .replace(/{name}/g, item.name)
            .replace(/{sub_money}/g, item.sub_money)
            .replace(/{min_money}/g, item.min_money)
            .replace(/{last}/g, item.last_number)
            .replace(/{number}/g, item.number)
            .replace(/{category}/g, item.category);
        }

        return tdHtml;
    },
    bindBtnAddYouHuiJuanToActivity: function() {
        var self    = this;
        $('#table-box a.btn-add-search-goo').click(function() {
            var id  = $(this).attr('data-id');
            self.appendYouHuiJuanList(id);
            $('#search-item-' + id).fadeOut('fast', function() {
                $(this).remove();
            });
        });
    },
    appendYouHuiJuanList: function(id) {
        var tpl             = $('#sort-youhuijuan-template').html();
        tpl                 = tpl.replace(/{name}/g, $('#name-' + id).text())
        .replace(/{id}/g, id)
        .replace(/{number}/g, $('#number-' + id).text())
        .replace(/{category}/g, $('#category-' + id).text())
        .replace(/{min_money}/g, $('#min-money-' + id).text())
        .replace(/{sub_money}/g, $('#sub-money-' + id).text())
        .replace(/{last_number}/g, $('#last-number-' + id).text());
        $('#youhuijuan-list').append(tpl);
        this.bindBtnYouHuiJuanItemDel();
    },
    bindBtnYouHuiJuanItemDel: function() {
        $('#youhuijuan-list a.btn-goods-item-del').unbind().click(function() {
            var id  = $(this).attr('data-id');
            if(!confirm('您真的要删除此项吗？')) {
                return;
            }
            $('#youhuijuan-item-' + id).fadeOut(200, function() {
                $(this).remove();
            });
        });
    },
    bindInfoFromSubmit: function() {
        $('#info-form').submit(function() {
            $('div.dd').each(function() {
                var $this       = $(this);
                var obj         = $this.nestable('serialize');
                var str         = JSON.stringify(obj);
                $this.find('input:hidden').val(str);
            });
        });
    },
    bindBtnGoodsSearchFormSubmit: function() {
        var self    = this;
        $('#goods-search-form').submit(function() {
            self.doSearchQueList(1);
            return false;
        });
    },
    doSearchQueList: function(page) {
        var self            = this;
        try {
            var keywords    = $('#goo-keywords').val();
            var discount    = $('#goo-discount').val();
            var type        = $('#goo-type').val();
            var brand       = $('#brand').val();
            if(!keywords && !type && !discount && !brand) {
                throw {dom: $('#goo-keywords'), message: '搜索条件不能全为空哦！'}
            }
            $.getJSON(
                queryUrl + 'admin/goods/asearch',
                {keywords: keywords, type: type, discount: discount, brand: brand, page: page},
                function(response) {
                    if(false === response.rs) {
                        return HHJsLib.warn(response.message);
                    }
                    $('#search-page').val(page + 1);
                    var tableTpl    = $('#search-result-template').html();
                    var itemHtml    = self.getSearchGoodsListHtml(response.data);
                    tableTpl        = tableTpl.replace(/{content}/g, itemHtml);
                    $('#goods-table-box').html(tableTpl);
                    HHJsLib.bindLightBox('#goods-table-box a.lightbox', cdnUrl + 'jquery/plugins/lightbox');
                    self.bindCheckAll();
                    self.initSearchTablePages(page, response);
                    self.bindBtnAddSearchGoodsToActivity();
                    self.bindBtnPreNextSearchPages(function(page) {
                        self.doSearchQueList(page);
                    });
                },
                'JSON'
            );
            return false;
        } catch(e) {
            return HHJsLib.warn(e);
        }
    },
    initSearchTablePages: function(page, response) {
        var prePage     = page - 1 > 0 ? page - 1 : 1;
        var nextPage    = page + 1 > response.totalPages ? response.totalPages : page + 1;
        $('#btn-btn-search-pre-page').attr('data-page', prePage);
        $('#btn-btn-search-next-page').attr('data-page', nextPage);
        $('#cur-page-info').html(page + ' / ' + response.totalPages);
        $('#btn-search-next-page,#btn-search-pre-page').attr('disabled', null);
        if(1 == response.totalPages) {
            $('#btn-search-next-page,#btn-search-pre-page').attr('disabled', 'disabled');
        } else if(1 >= page) {
            $('#btn-search-pre-page').attr('disabled', 'disabled');
        } else if (page == response.totalPages) {
            $('#btn-search-next-page').attr('disabled', 'disabled');
        }
    },
    bindBtnPreNextSearchPages: function(callback) {
        $('#btn-search-next-page,#btn-search-pre-page').click(function() {
            if(null != $(this).attr('disabled')) {
                return false;
            }
            var page    = $(this).attr('data-page');
            if('undefined' !== typeof(callback)) {
                return callback(page);
            }
        });
    },
    bindBtnAddSearchGoodsToActivity: function() {
        var self    = this;
        $('#goods-table-box a.btn-add-search-goo').click(function() {
            var id  = $(this).attr('data-id');
            self.appendGoodsList(id);
            $('#search-goo-item-' + id).fadeOut('fast', function() {
                $(this).remove();
            });
            self.bindDrop('#goods-list-box-' + id);
        });
    },
    appendGoodsList: function(id) {
        var tpl             = $('#sort-goods-template').html();
        var curQueTypeId    = $('#cur-goods-type-id').val();
        var goods           = $('.goods-list-box').children('ol').find('#goods-' + id).length;
        if(goods > 0){
            return false;
        }
        tpl                 = tpl.replace(/{goods}/g, $('#goods-' + id).text())
        .replace(/{number}/g, $('#number-' + id).text())
        .replace(/{name}/g, $('#name-' + id).text())
        .replace(/{id}/g, id)
        .replace(/{min_price}/g, $('#min-price-' + id).text())
        .replace(/{category}/g, $('#category-' + id).text())
        .replace(/{img}/g, $('#img-' + id).attr('data-small-src'))
        .replace(/{src}/g, $('#img-' + id).attr('data-src'))
        .replace(/{max_price}/g, $('#max-price-' + id).text())
        .replace(/{sale}/g, $('#sale-' + id).text())
        .replace(/{discount}/g, $('#discount-' + id).text());
        $('#goods-list-' + curQueTypeId).append(tpl);
        this.bindBtnGoodsItemDel('#goods-' + id + ' a.btn-goods-item-del');
        $('#goods-list-' + curQueTypeId).nestable({'maxDepth': 1});
    },
    bindBtnGoodsItemDel: function(dom) {
        var self    = this;
        $(dom).click(function() {
            var id  = $(this).attr('data-id');
            if(!confirm('您真的要删除此项吗？注意：删除后将无法找回！')) {
                return false;
            }
            var $parent     = $('#goods-' + id);
            var status      = $parent.attr('data-status');
            if(1 == status) {
                $parent.fadeOut('fast', function() {
                    $(this).remove();
                });
                return;
            }
            HHJsLib.info('正在努力删除中...');
            var title   = $(this).parents('div.goods-list-box').siblings('div.control-group').find('input[name="title[]"]').val()
            $.getJSON(
                queryUrl + 'admin/couxiao/adelbyactitem',
                {id: id, act_id: $('#id').val(), title: title},
                function(response) {
                    if(false === response.rs) {
                        return HHJsLib.warn(response.message);
                    }
                    $parent.fadeOut('fast', function() {
                        $(this).remove();
                    });
                }
            );
        });
    },
    getSearchGoodsListHtml: function(list) {
        if(!list || 1 > list.length) {
            return '<tr><td colspan="11"><div  class="text-center">没有搜索到相关产品哦～</div></td></tr>';
        }
        var itemTpl = $('#result-item-template').html();
        var tdHtml  = '';
        for(var ele in list) {
            var item    = list[ele];
            tdHtml      += itemTpl.replace(/{id}/g, item.id)
            .replace(/{name}/g, item.name)
            .replace(/{category}/g, item.category)
            .replace(/{min_price}/g, item.min_price)
            .replace(/{max_price}/g, item.max_price)
            .replace(/{src}/g, item.image_path)
            .replace(/{img}/g, item.small_img)
            .replace(/{max_price}/g, item.max_price)
            .replace(/{sale}/g, item.total_orders)
            .replace(/{number}/g, item.total_number)
            .replace(/{discount}/g, item.discount);
        }

        return tdHtml;
    },
    bindBtnGoodsAdd: function(dom) {
        var self    = this;
        $(dom).click(function() {
            var id  = $(this).attr('data-id');
            var body= $('#search-goods-body-template').html();
            $('#modal-body').html(body);
            $('#myModalLabel').html('添加产品');
            $('#modal-footer').html($('#search-footer-template').html());
            $('#myModal').modal('show');
            $('#cur-goods-type-id').val(id);
            self.bindBtnBatch();
            self.bindBtnGoodsSearchFormSubmit();
        });
    },
    bindBtnGoodsDel: function(dom) {
        $(dom).click(function() {
            if(!confirm('您真的要删除此项吗？注意：删除后将不能恢复哦！')) {
                return;
            }
            var id      = $(this).attr('data-id');
            var status  = $('#panel-' + id).attr('data-status');
            if(1 == status) {
                $('#panel-' + id).fadeOut('fast', function() {
                    $(this).remove();
                });
                return;
            }
            var ids     = $('#goods-list-box-' + id).nestable('serialize');
            var title   = $('#collapse-' + id).find('div.control-group').find('input[name="title[]"]').val();
            $.getJSON(
                queryUrl + 'admin/couxiao/adelbyactivity',
                {ids: JSON.stringify(ids), act_id: $('#id').val(), title: title},
                function(response) {
                    if(false === response.rs) {
                        return HHJsLib.warn(response.message);
                    }
                    HHJsLib.succeed('删除成功！共删除' + response.total + '条数据。');
                    $('#panel-' + id).fadeOut('fast', function() {
                        $(this).remove();
                    });
                }
            );
        });
    },
    bindBtnAddNewGoodsType: function() {
        var self    = this;
        $('#btn-add-new-goods-type').click(function() {
            var t   = (new Date()).getTime();
            var tpl = $('#goods-type-template').html();
            tpl     = tpl.replace(/{id}/g, t);
            $('#accordion').append(tpl);
            self.bindBtnGoodsDel("#panel-" + t + ' a.btn-goods-del');
            self.bindBtnGoodsAdd("#panel-" + t + ' a.btn-goods-add');
            self.bindDrop();
        });
    },
    bindCheckAll: function() {
        $('table th input:checkbox').on('click' , function(){
            var that = this;
            $(this).closest('table').find('tr > td:first-child input:checkbox')
                .each(function(){
                    this.checked = that.checked;
                    $(this).closest('tr').toggleClass('selected');
                });
        });
    },
    bindBtnBatch: function() {
        var self    = this;
        $('#myModal a.btn-add-batch').on('click', function(){
            try{
                var items       = $("#search-goo-list input:checked");
                if(typeof items.length == 'undefined' || items.length < 1 ) {
                    return HHJsLib.warn("请选择要添加的产品！");
                }
                items.each(function(){
                    var id  = $(this).val();
                    self.appendGoodsList(id);
                    $('#search-goo-item-' + id).fadeOut('fast', function() {
                        $(this).remove();
                    });
                });
                var id  = $(this).siblings('#cur-goods-type-id').val();
                self.bindDrop('#goods-list-box-' + id);
            } catch(e) {
                return HHJsLib.warn(e);
            }
        });
    },
    bindDrop: function(target) {
        target  = 'undefined' == typeof(target) ? 'div.dd' : target;
        $(target).nestable({'maxDepth': 1}).on('change', function() {
            var that        = $(this);
            var obj         = that.nestable('serialize');
            var str         = window.JSON.stringify(obj);
            that.find('input:hidden').val(str);
        });
    },
    bindBtnInfoFormSubmit: function(){
        $("#info-form").bind('submit', function(){
            try{
                if($('#name').val() == ''){
                    $('#name').focus();
                    return false;
                }
                if(HHJsLib.editor.content.getContent() == ''){
                    HHJsLib.editor.content.focus();
                    return false;
                }
                if($('#number').val() == ''){
                    $('#number').focus();
                    return false;
                }
                HHJsLib.isEmptyByDom('#image_path', '封面图片');
                var next = false;
                $('#accordion').children('div.panel').each(function(index){
                    var $that   = $(this);
                    var name    = $that.find('input[name="title[]"]').val();
                    if(name == ''){
                        next = true;
                        return HHJsLib.warn('第' + (index + 1) + '个产品块标题不能为空');
                    }
                    var len = $that.find('div.goods-list-box').find('li.dd-item').length;
                    if(1 > len){
                        next = true;
                        return HHJsLib.warn('第' + (index + 1) + '个产品块活动产品不能为空');
                    }
                });
                if(next){
                    return false;
                }
            }catch(e) {
                return HHJsLib.warn(e);
            }
        });
    }
});
